package com.example.pro1;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener{
	ListView mListView;
	Button btn_request_json;
	public List<Contacts> list;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				
				 mListView.setAdapter(new MyAdapter(this,list));	
				
				break;

			default:
				break;
			}
		}
	};
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
		initEvent();
		
    }

	private void initEvent() {
		// TODO Auto-generated method stub
		btn_request_json.setOnClickListener(this);
		
	}

	private void initView() {
		// TODO Auto-generated method stub
		mListView=(ListView) findViewById(R.id.listView1);
		btn_request_json=(Button)findViewById(R.id.btn_request_json);
		
	}

	public void onClick(View v){
		switch(v.getId()){
		case R.id.btn_request_json:
			OkHttpClient client2 = new OkHttpClient();
			Request request2 = new Request.Builder()
					.url("http://176.122.140.84/contact.json").get().build();
			client2.newCall(request2).enqueue(new Callback() {

				@Override
				public void onResponse(Call arg0, Response response)
						throws IOException {
					// TODO Auto-generated method stub
					InputStream in = response.body().byteStream();
					Bitmap bitmap = BitmapFactory.decodeStream(in);
					Message msg = Message.obtain();
					msg.what = 1;
					msg.obj = bitmap;
					handler.sendMessage(msg);
					
					 list = new ArrayList<Contacts>();
					String json = response.body().string();
					Gson gson = new Gson();
					list = gson.fromJson(json,
							new TypeToken<List<Contacts>>(){}.getType());
					Log.d("demo",  gson.fromJson(json, null)+"");
					
					  
				}

				@Override
				public void onFailure(Call arg0, IOException arg1) {
					// TODO Auto-generated method stub

				}
			});
			break;
		default:
			break;
		
		}
	}
   
    
}
